package com.batunite.livedatabinding.views

import android.graphics.Rect
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.RecyclerView

class GridSpacingItemDecoration(private val spanCount: Int, private val spacing: Int) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        // item 位置
        val position = parent.getChildAdapterPosition(view)
        // item 所在列
        val column = position % spanCount
        // 包含边缘
        if (true) {
            // 设 spacing = 18 spanCount = 3
            // 第0列 left = s = 18 right = 18 / 3 = 6
            // 第1列 left = s - s/c = 18 - 6 = 12 right = 18 / 3 * 2= 12
            // 第2列 left = s - s/c * 2 = 18 - 6 * 2 = 6 right = 18 / 3 * 3= 18
            outRect.left = spacing - column * spacing / spanCount
            outRect.right = (column + 1) * spacing / spanCount
            Log.d(">>>>", "ItemOffsets: pos $position column $column left ${outRect.left}  right ${outRect.right}")
            if (position < spanCount) {
                outRect.top = spacing
            }
            outRect.bottom = spacing
        } else {
            outRect.left = column * spacing / spanCount
            outRect.right = spacing - (column + 1) * spacing / spanCount
            if (position >= spanCount) {
                outRect.top = spacing
            }
        }
    }
}
